<template>
  <el-form ref="genInfoForm" :model="info" :rules="rules" label-width="150px">
    <!-- 使用清晰的网格结构整理表单项 -->
    <el-card class="box-card" shadow="hover" style="margin-bottom: 20px;" :class="{'is-collapsed': !cardVisible.basicInfo}">
      <div slot="header" class="clearfix">
        <span><i class="el-icon-document" style="margin-right: 5px;"></i>基本信息</span>
        <i class="el-icon-arrow-up collapse-icon" v-if="cardVisible.basicInfo" @click="toggleCard('basicInfo')"></i>
        <i class="el-icon-arrow-down collapse-icon" v-else @click="toggleCard('basicInfo')"></i>
      </div>
      <el-row :gutter="20" v-show="cardVisible.basicInfo">
        <el-col :span="12">
          <el-form-item label="表名称" prop="tableName">
            <el-input placeholder="请输入表名称" v-model="info.tableName" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="表描述" prop="tableComment">
            <el-input placeholder="请输入" v-model="info.tableComment" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="实体类名称" prop="className">
            <el-input placeholder="请输入" v-model="info.className" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="作者" prop="functionAuthor">
            <el-input placeholder="请输入" v-model="info.functionAuthor" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>

    <el-card class="box-card" shadow="hover" style="margin-bottom: 20px;" :class="{'is-collapsed': !cardVisible.genConfig}">
      <div slot="header" class="clearfix">
        <span><i class="el-icon-menu" style="margin-right: 5px;"></i>基本生成配置</span>
        <i class="el-icon-arrow-up collapse-icon" v-if="cardVisible.genConfig" @click="toggleCard('genConfig')"></i>
        <i class="el-icon-arrow-down collapse-icon" v-else @click="toggleCard('genConfig')"></i>
      </div>
      <el-row :gutter="20" v-show="cardVisible.genConfig">
        <!-- 上级菜单（置于首位并突出显示） -->
        <el-col :span="24" style="margin-bottom: 15px;">
          <el-form-item class="important-form-item">
            <span slot="label">
              <b>上级菜单</b>
              <el-tooltip content="分配到指定菜单下，例如 系统管理" placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </span>
            <treeselect
              :append-to-body="true"
              v-model="info.parentMenuId"
              :options="menus"
              :normalizer="normalizer"
              :show-count="true"
              placeholder="请选择系统菜单"
              class="menu-select"
            />
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item prop="tplCategory">
            <span slot="label">生成模板</span>
            <el-select v-model="info.tplCategory" @change="tplSelectChange" style="width: 100%;">
              <el-option label="单表（增删改查）" value="crud" />
              <el-option label="树表（增删改查）" value="tree" />
              <el-option label="主子表（增删改查）" value="sub" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item prop="packageName">
            <span slot="label">
              生成包路径
              <el-tooltip content="生成在哪个java包下，例如 com.hello.system" placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </span>
            <el-input v-model="info.packageName" @input="onPackageNameInput" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item prop="moduleName">
            <span slot="label">
              生成模块名
              <el-tooltip content="可理解为子系统名，例如 system" placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </span>
            <el-input v-model="info.moduleName" @input="onModuleNameInput" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item prop="businessName">
            <span slot="label">
              生成业务名
              <el-tooltip content="可理解为功能英文名，例如 user" placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </span>
            <el-input v-model="info.businessName" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item prop="functionName">
            <span slot="label">
              生成功能名
              <el-tooltip content="用作类描述，例如 用户" placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </span>
            <el-input v-model="info.functionName" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item prop="genType">
            <span slot="label">
              生成代码方式
              <el-tooltip content="默认为自定义生成路径，也可以选择zip压缩包下载" placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </span>
            <el-radio-group v-model="info.genType">
              <el-radio label="1">自定义路径</el-radio>
              <el-radio label="0">zip压缩包</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item prop="mergeMode">
            <span slot="label">
              代码合并模式
              <el-tooltip content="选择代码生成模式，合并模式会保留已存在文件中的自定义代码，覆盖模式会完全替换已存在的文件" placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </span>
            <el-radio-group v-model="info.mergeMode">
              <el-radio label="1">智能合并</el-radio>
              <el-radio label="0">覆盖模式</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>

    <el-card class="box-card" shadow="hover" style="margin-bottom: 20px;" v-if="info.genType == '1'" :class="{'is-collapsed': !cardVisible.pathConfig}">
      <div slot="header" class="clearfix">
        <span><i class="el-icon-folder-opened" style="margin-right: 5px;"></i>生成路径配置</span>
        <i class="el-icon-arrow-up collapse-icon" v-if="cardVisible.pathConfig" @click="toggleCard('pathConfig')"></i>
        <i class="el-icon-arrow-down collapse-icon" v-else @click="toggleCard('pathConfig')"></i>
      </div>
      <el-row :gutter="20" v-show="cardVisible.pathConfig">
        <el-col :span="24">
          <el-form-item prop="genPath">
            <span slot="label">
              工作空间路径
              <el-tooltip content="填写项目工作空间的绝对路径，所有代码默认生成位置，也可单独配置前后端路径" placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </span>
            <el-input v-model="info.genPath" :title="info.genPath" @input="onGenPathInput">
              <template slot="prepend">
                <el-button icon="el-icon-edit" type="primary" size="mini" @click="editPath('genPath')" title="修改路径"></el-button>
              </template>
              <template slot="append">
                <el-button-group>
                  <el-button type="primary" icon="el-icon-download" @click="generateAllCode" title="生成前端和后端代码">生成全部</el-button>
                  <el-tag v-if="info.mergeMode === '1'" type="success" size="mini" effect="dark">智能合并</el-tag>
                  <el-tag v-else type="warning" size="mini" effect="dark">覆盖模式</el-tag>
                  <el-dropdown>
                    <el-button type="primary">
                      路径选项
                      <i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item @click.native="setProjectRootPath">使用项目根路径</el-dropdown-item>
                      <el-dropdown-item @click.native="setDefaultPath">恢复默认工作空间路径</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </el-button-group>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item prop="backendGenPath">
            <span slot="label">
              后端代码路径
              <el-tooltip content="填写后端代码生成的绝对路径，不填则使用默认路径" placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </span>
            <el-input v-model="info.backendGenPath" :title="info.backendGenPath" @input="onBackendPathInput">
              <template slot="prepend">
                <el-button icon="el-icon-edit" type="primary" size="mini" @click="editPath('backendGenPath')" title="修改路径"></el-button>
              </template>
              <template slot="append">
                <el-button-group>
                  <el-button type="primary" icon="el-icon-download" @click="generateBackendCode" title="只生成后端代码">生成后端</el-button>
                  <el-tag v-if="info.mergeMode === '1'" type="success" size="mini" effect="dark">智能合并</el-tag>
                  <el-tag v-else type="warning" size="mini" effect="dark">覆盖模式</el-tag>
                  <el-dropdown>
                    <el-button type="primary">
                      常用路径
                      <i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item @click.native="info.backendGenPath = info.genPath + '/java'">使用工作空间路径/java</el-dropdown-item>
                      <el-dropdown-item @click.native="info.backendGenPath = ''">清空路径</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </el-button-group>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item prop="frontendGenPath">
            <span slot="label">
              前端代码路径
              <el-tooltip content="填写前端代码生成的绝对路径，不填则使用默认路径" placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </span>
            <el-input v-model="info.frontendGenPath" :title="info.frontendGenPath" @input="onFrontendPathInput">
              <template slot="prepend">
                <el-button icon="el-icon-edit" type="primary" size="mini" @click="editPath('frontendGenPath')" title="修改路径"></el-button>
              </template>
              <template slot="append">
                <el-button-group>
                  <el-button type="primary" icon="el-icon-download" @click="generateFrontendCode" title="只生成前端代码">生成前端</el-button>
                  <el-tag v-if="info.mergeMode === '1'" type="success" size="mini" effect="dark">智能合并</el-tag>
                  <el-tag v-else type="warning" size="mini" effect="dark">覆盖模式</el-tag>
                  <el-dropdown>
                    <el-button type="primary">
                      常用路径
                      <i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item @click.native="info.frontendGenPath = info.genPath + '/ui'">使用工作空间路径/ui</el-dropdown-item>
                      <el-dropdown-item @click.native="info.frontendGenPath = ''">清空路径</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </el-button-group>
              </template>
            </el-input>
          </el-form-item>
          
          <!-- 文件目录结构预览 -->
          <el-form-item label="生成文件预览" class="structure-preview-item">
            <div style="display: flex; justify-content: space-between; margin-bottom: 10px;">
              <el-button type="primary" icon="el-icon-view" size="medium" @click="previewCode">预览代码</el-button>
              <div>
                <el-button-group size="mini">
                  <el-button 
                    :type="allExpanded ? 'info' : 'primary'" 
                    :icon="allExpanded ? 'el-icon-arrow-up' : 'el-icon-arrow-down'" 
                    @click="toggleAllStructures" 
                    plain>
                    {{ allExpanded ? '折叠全部' : '展开全部' }}
                  </el-button>
                  <el-button type="success" icon="el-icon-refresh" @click="refreshAllStructures" plain>刷新结构</el-button>
                </el-button-group>
              </div>
            </div>
            <el-row :gutter="12" class="file-structure-preview">
              <!-- 后端代码结构 -->
              <el-col :span="8" style="margin-bottom: 15px;">
              <el-card class="box-card" shadow="hover">
                <div slot="header" class="clearfix">
                    <span>
                      <i class="el-icon-s-platform" style="color: #409EFF;"></i> 后端代码结构
                  <el-tooltip content="Java后端代码文件结构" placement="top">
                    <i class="el-icon-question" style="margin-left: 5px;"></i>
                  </el-tooltip>
                    </span>
                    <el-button 
                      size="mini"
                      style="float: right; padding: 3px 8px;" 
                      :type="backendCollapsed ? 'primary' : 'info'" 
                      @click="toggleBackendCollapse">
                      <i :class="backendCollapsed ? 'el-icon-arrow-down' : 'el-icon-arrow-up'"></i>
                      {{ backendCollapsed ? '展开' : '折叠' }}
                    </el-button>
                </div>
                  <div v-show="!backendCollapsed">
                    <el-tag size="mini" effect="plain" type="primary" style="margin-bottom: 10px; display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                      路径: {{ info.backendGenPath || info.genPath || '/' }}
                    </el-tag>
                <el-tree
                  :data="backendStructure"
                  :props="defaultProps"
                  :expand-on-click-node="false"
                      default-expand-all
                      ref="backendTree"
                  node-key="id">
                  <span class="custom-tree-node" slot-scope="{ node, data }">
                    <span>
                      <i :class="data.isDirectory ? 'el-icon-folder' : 'el-icon-document'" 
                         :style="{ color: data.isDirectory ? '#fac858' : '#409EFF' }"></i>
                      {{ node.label }}
                    </span>
                  </span>
                </el-tree>
                    <div class="tree-operations" v-if="!backendCollapsed && backendStructure.length > 0">
                      <el-button 
                        size="mini" 
                        type="primary"
                        plain
                        :icon="isBackendTreeExpanded ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
                        @click="toggleTreeExpand('backendTree')">
                        {{ isBackendTreeExpanded ? '折叠' : '展开' }}
                      </el-button>
                    </div>
                  </div>
              </el-card>
              </el-col>
              
              <!-- 前端代码结构 -->
              <el-col :span="8" style="margin-bottom: 15px;">
              <el-card class="box-card" shadow="hover">
                <div slot="header" class="clearfix">
                    <span>
                      <i class="el-icon-s-grid" style="color: #67C23A;"></i> 前端代码结构
                  <el-tooltip content="Vue前端代码文件结构" placement="top">
                    <i class="el-icon-question" style="margin-left: 5px;"></i>
                  </el-tooltip>
                    </span>
                    <el-button 
                      size="mini"
                      style="float: right; padding: 3px 8px;" 
                      :type="frontendCollapsed ? 'primary' : 'info'" 
                      @click="toggleFrontendCollapse">
                      <i :class="frontendCollapsed ? 'el-icon-arrow-down' : 'el-icon-arrow-up'"></i>
                      {{ frontendCollapsed ? '展开' : '折叠' }}
                    </el-button>
                </div>
                  <div v-show="!frontendCollapsed">
                    <el-tag size="mini" effect="plain" type="success" style="margin-bottom: 10px; display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                      路径: {{ info.frontendGenPath || info.genPath || '/' }}
                    </el-tag>
                <el-tree
                  :data="frontendStructure"
                  :props="defaultProps"
                  :expand-on-click-node="false"
                      default-expand-all
                      ref="frontendTree"
                  node-key="id">
                  <span class="custom-tree-node" slot-scope="{ node, data }">
                    <span>
                      <i :class="data.isDirectory ? 'el-icon-folder' : 'el-icon-document'" 
                         :style="{ color: data.isDirectory ? '#fac858' : '#67C23A' }"></i>
                      {{ node.label }}
                    </span>
                  </span>
                </el-tree>
                    <div class="tree-operations" v-if="!frontendCollapsed && frontendStructure.length > 0">
                      <el-button 
                        size="mini" 
                        type="primary"
                        plain
                        :icon="isFrontendTreeExpanded ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
                        @click="toggleTreeExpand('frontendTree')">
                        {{ isFrontendTreeExpanded ? '折叠' : '展开' }}
                      </el-button>
                    </div>
                  </div>
              </el-card>
              </el-col>
              
              <!-- 配置代码结构 -->
              <el-col :span="8">
              <el-card class="box-card" shadow="hover">
                <div slot="header" class="clearfix">
                    <span>
                      <i class="el-icon-setting" style="color: #E6A23C;"></i> 配置代码结构
                  <el-tooltip content="SQL和配置文件结构" placement="top">
                    <i class="el-icon-question" style="margin-left: 5px;"></i>
                  </el-tooltip>
                    </span>
                    <el-button 
                      size="mini"
                      style="float: right; padding: 3px 8px;" 
                      :type="configCollapsed ? 'primary' : 'info'" 
                      @click="toggleConfigCollapse">
                      <i :class="configCollapsed ? 'el-icon-arrow-down' : 'el-icon-arrow-up'"></i>
                      {{ configCollapsed ? '展开' : '折叠' }}
                    </el-button>
                </div>
                  <div v-show="!configCollapsed">
                <el-tree
                  :data="configStructure"
                  :props="defaultProps"
                  :expand-on-click-node="false"
                      default-expand-all
                      ref="configTree"
                  node-key="id">
                  <span class="custom-tree-node" slot-scope="{ node, data }">
                    <span>
                      <i :class="data.isDirectory ? 'el-icon-folder' : 'el-icon-document'" 
                         :style="{ color: data.isDirectory ? '#fac858' : '#E6A23C' }"></i>
                      {{ node.label }}
                    </span>
                  </span>
                </el-tree>
                    <div class="tree-operations" v-if="!configCollapsed && configStructure.length > 0">
                      <el-button 
                        size="mini" 
                        type="primary"
                        plain
                        :icon="isConfigTreeExpanded ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
                        @click="toggleTreeExpand('configTree')">
                        {{ isConfigTreeExpanded ? '折叠' : '展开' }}
                      </el-button>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>

    <!-- 系统文件目录选择器对话框 -->
    <el-dialog title="选择目录" :visible.sync="directoryDialogVisible" width="700px" append-to-body custom-class="directory-dialog">
      <div class="directory-tree-container">
        <el-form :inline="true" size="small" class="directory-form">
          <el-form-item class="path-item">
            <el-input v-model="currentPath" placeholder="当前路径" readonly style="width: 100%" :title="currentPath">
              <el-button slot="prepend" icon="el-icon-refresh" @click="loadDirectories(currentPath)" title="刷新"></el-button>
              <el-button slot="append" icon="el-icon-back" @click="navigateUp" title="返回上一级"></el-button>
            </el-input>
          </el-form-item>
        </el-form>
        <div class="directory-list">
          <el-table 
            :data="directories" 
            style="width: 100%" 
            height="300" 
            highlight-current-row 
            @row-click="selectDirectory"
            :header-cell-style="{background:'#f6f6f6'}"
          >
            <el-table-column prop="name" label="目录名称" min-width="65%">
              <template slot-scope="scope">
                <div class="dir-item">
                  <i class="el-icon-folder" style="color: #fac858; margin-right: 5px;"></i> 
                  <span>{{ scope.row.name }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="35%" align="center">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" plain @click.stop="enterDirectory(scope.row)">
                  <i class="el-icon-folder-opened"></i> 打开
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="directoryDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmDirectorySelection" :disabled="!selectedPath">确 定</el-button>
      </div>
    </el-dialog>
    
    <!-- 树形表格配置 -->
    <el-card class="box-card" shadow="hover" style="margin-bottom: 20px;" v-show="info.tplCategory == 'tree'">
      <div slot="header" class="clearfix">
        <span><i class="el-icon-share" style="margin-right: 5px;"></i>树形结构配置</span>
      </div>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item>
            <span slot="label">
              树编码字段
              <el-tooltip content="树显示的编码字段名， 如：dept_id" placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </span>
            <el-select v-model="info.treeCode" placeholder="请选择" style="width: 100%;">
              <el-option
                v-for="(column, index) in info.columns"
                :key="index"
                :label="column.columnName + '：' + column.columnComment"
                :value="column.columnName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item>
            <span slot="label">
              树父编码字段
              <el-tooltip content="树显示的父编码字段名， 如：parent_Id" placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </span>
            <el-select v-model="info.treeParentCode" placeholder="请选择" style="width: 100%;">
              <el-option
                v-for="(column, index) in info.columns"
                :key="index"
                :label="column.columnName + '：' + column.columnComment"
                :value="column.columnName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item>
            <span slot="label">
              树名称字段
              <el-tooltip content="树节点的显示名称字段名， 如：dept_name" placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </span>
            <el-select v-model="info.treeName" placeholder="请选择" style="width: 100%;">
              <el-option
                v-for="(column, index) in info.columns"
                :key="index"
                :label="column.columnName + '：' + column.columnComment"
                :value="column.columnName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>

    <!-- 子表关联配置 -->
    <el-card class="box-card" shadow="hover" style="margin-bottom: 20px;" v-show="info.tplCategory == 'sub'">
      <div slot="header" class="clearfix">
        <span><i class="el-icon-connection" style="margin-right: 5px;"></i>关联子表配置</span>
      </div>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item>
            <span slot="label">
              关联子表的表名
              <el-tooltip content="关联子表的表名， 如：sys_user" placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </span>
            <el-select v-model="info.subTableName" placeholder="请选择" @change="subSelectChange" style="width: 100%;">
              <el-option
                v-for="(table, index) in tables"
                :key="index"
                :label="table.tableName + '：' + table.tableComment"
                :value="table.tableName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item>
            <span slot="label">
              子表关联的外键名
              <el-tooltip content="子表关联的外键名， 如：user_id" placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </span>
            <el-select v-model="info.subTableFkName" placeholder="请选择" style="width: 100%;">
              <el-option
                v-for="(column, index) in subColumns"
                :key="index"
                :label="column.columnName + '：' + column.columnComment"
                :value="column.columnName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>

    <el-dialog :visible.sync="pathInputVisible" title="编辑路径" width="600px" append-to-body>
      <el-form :model="{ pathValue: pathInputValue }">
        <el-form-item label="路径" label-width="80px">
          <el-input v-model="pathInputValue" placeholder="请输入完整路径" clearable>
            <template slot="append">
              <el-button icon="el-icon-folder-opened" @click="showDirectoryDialog(currentEditPathType)">选择</el-button>
            </template>
          </el-input>
        </el-form-item>
        <div class="path-tips">
          <el-alert
            title="提示：输入路径必须是有效的目录路径，否则代码生成可能会失败"
            type="warning"
            :closable="false">
          </el-alert>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="pathInputVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEditedPath">确 定</el-button>
      </div>
    </el-dialog>
  </el-form>
</template>

<script>
import { getSystemDirectories, getWorkspace, getProjectStructure, previewTable, genCode } from "@/api/tool/gen";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { debounce } from 'lodash';

export default {
  components: { Treeselect },
  props: {
    info: {
      type: Object,
      default: null
    },
    tables: {
      type: Array,
      default: null
    },
    menus: {
      type: Array,
      default: []
    },
  },
  data() {
    return {
      // 卡片显示控制
      cardVisible: {
        basicInfo: true,
        genConfig: true,
        pathConfig: true
      },
      subColumns: [],
      rules: {
        tplCategory: [
          { required: true, message: "请选择生成模板", trigger: "blur" }
        ],
        packageName: [
          { required: true, message: "请输入生成包路径", trigger: "blur" }
        ],
        moduleName: [
          { required: true, message: "请输入生成模块名", trigger: "blur" }
        ],
        businessName: [
          { required: true, message: "请输入生成业务名", trigger: "blur" }
        ],
        functionName: [
          { required: true, message: "请输入生成功能名", trigger: "blur" }
        ],
      },
      // 目录选择器相关
      directoryDialogVisible: false,
      directories: [],
      currentPath: "",
      selectedPath: "",
      pathType: "genPath",  // 默认为通用路径
      // 文件结构相关
      backendStructure: [],
      frontendStructure: [],
      configStructure: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 路径修改前的值
      originalPath: {
        genPath: '',
        backendGenPath: '',
        frontendGenPath: '',
        moduleName: '' // 添加模块名的原始值记录
      },
      // 路径输入对话框
      pathInputVisible: false,
      pathInputValue: '',
      currentEditPathType: '',
      // 防抖处理的路径更新函数
      debouncedUpdatePaths: null,
      // 创建模块名变化的防抖函数
      debouncedModuleNameChange: null,
      // 创建包路径变化的防抖函数
      debouncedPackageNameChange: null,
      // 后端代码结构折叠状态
      backendCollapsed: false,
      // 前端代码结构折叠状态
      frontendCollapsed: false,
      // 配置代码结构折叠状态
      configCollapsed: false,
      // 添加树的展开状态
      isBackendTreeExpanded: true,
      isFrontendTreeExpanded: true,
      isConfigTreeExpanded: true,
      // 添加全部展开状态
      allExpanded: false,
      // 树节点图标映射
      fileIconMap: {
        'java': 'el-icon-s-platform',
        'xml': 'el-icon-tickets',
        'js': 'el-icon-s-opportunity',
        'vue': 'el-icon-s-grid',
        'html': 'el-icon-document',
        'css': 'el-icon-s-cooperation',
        'sql': 'el-icon-notebook-2',
        'json': 'el-icon-document-copy',
        'default': 'el-icon-document'
      }
    };
  },
  created() {
    this.generateFileStructure();
    
    // 默认设置为自定义路径
    if (!this.info.genType) {
      this.info.genType = "1";
    }
    
    // 默认设置为合并模式
    if (this.info.mergeMode === undefined) {
      this.info.mergeMode = "1";
    }
    
    // 只有在真正为空或无效时才设置默认路径
    if (!this.info.genPath || this.info.genPath === '/dev-api') {
      this.setProjectRootPathSync();
    }
    
    // 确保前后端路径合理设置
    if (!this.info.backendGenPath) {
      this.info.backendGenPath = this.info.genPath || '/';
    }
    if (!this.info.frontendGenPath) {
      this.info.frontendGenPath = this.info.genPath || '/';
    }
    
    // 默认设置上级菜单为系统管理
    if (!this.info.parentMenuId) {
      this.info.parentMenuId = "1"; // 系统管理的ID
    }

    // 创建防抖函数
    this.debouncedUpdatePaths = debounce(this.updateRelatedPaths, 300);
    
    // 创建模块名变化的防抖函数，减少延迟时间使响应更及时
    this.debouncedModuleNameChange = debounce((val) => {
      // 获取旧值用于比较
      const oldVal = this.originalPath.moduleName || '';
      
      // 处理联动变化
      if (val !== oldVal) {
        this.handleModuleNameChange(val, oldVal);
      }
    }, 200); // 减少延迟时间
    
    // 创建包路径变化的防抖函数
    this.debouncedPackageNameChange = debounce((val) => {
      // 更新包路径时，可能需要联动更新其他字段
      // 例如从包路径中提取模块名
      if (val && val.includes('.')) {
        const parts = val.split('.');
        const lastPart = parts[parts.length - 1];
        
        // 如果模块名为空，则从包路径中提取
        if (!this.info.moduleName) {
          this.info.moduleName = lastPart;
          this.originalPath.moduleName = lastPart;
          console.log(`已从包路径提取模块名: ${lastPart}`);
          
          // 同时更新后端路径中的模块名部分
          if (this.info.backendGenPath) {
            // 获取路径分隔符
            let separator = '/';
            if (this.info.backendGenPath.includes('\\')) {
              separator = '\\';
            }
            
            // 更新后端路径中的模块名
            const modulePattern = new RegExp(`${separator}hello-modules${separator}hello-[^${separator}]+`);
            if (modulePattern.test(this.info.backendGenPath)) {
              this.info.backendGenPath = this.info.backendGenPath.replace(modulePattern, `${separator}hello-modules${separator}hello-${lastPart}`);
              console.log(`已根据包路径更新后端路径为: ${this.info.backendGenPath}`);
            }
          }
        }
      }
    }, 300);
    
    // 初始化记录模块名原始值
    if (this.info.moduleName) {
      this.originalPath.moduleName = this.info.moduleName;
    }
  },
  watch: {
    'info.subTableName': function(val) {
      this.setSubTableColumns(val);
    },
    'info.tplCategory': function() {
      this.generateFileStructure();
    },
    'info.packageName': function() {
      this.generateFileStructure();
    },
    'info.moduleName': function(newVal, oldVal) {
      if (newVal !== oldVal) {
        // 立即更新后端路径
        if (this.info.backendGenPath) {
          // 获取路径分隔符
          let separator = '/';
          if (this.info.backendGenPath.includes('\\')) {
            separator = '\\';
          }
          
          // 直接构建新的后端路径
          const basePath = this.info.genPath || '';
          this.info.backendGenPath = `${basePath}${separator}hello-modules${separator}hello-${newVal}`;
          console.log(`监听器：后端路径已更新为 ${this.info.backendGenPath}`);
        }
        
        // 生成文件结构预览
      this.generateFileStructure();
      }
    },
    'info.businessName': function() {
      this.generateFileStructure();
    },
    'info.className': function() {
      this.generateFileStructure();
    },
    // 添加对路径的监听，并使用防抖函数
    'info.genPath': function(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.debouncedUpdatePaths('genPath', newVal, oldVal);
      }
    },
    'info.backendGenPath': function(newVal, oldVal) {
      if (newVal !== oldVal) {
        // 重新生成文件结构预览
        this.generateFileStructure();
      }
    },
    'info.frontendGenPath': function(newVal, oldVal) {
      if (newVal !== oldVal) {
        // 重新生成文件结构预览
        this.generateFileStructure();
      }
    },
    // 监听上级菜单ID变化
    'info.parentMenuId': function(newVal, oldVal) {
      if (newVal !== oldVal) {
        // 查找菜单信息并打印
        const findMenuInfo = (menus, id) => {
          for (let i = 0; i < menus.length; i++) {
            if (menus[i].menuId == id) {
              // 找到匹配的菜单
              const menuPath = menus[i].path || '';
              const menuName = menus[i].menuName || '';
              const menuType = menus[i].menuType || '';
              const menuTypeText = menuType === 'M' ? '目录' : menuType === 'C' ? '菜单' : '按钮';
              const component = menus[i].component || '';
              
              console.log('===== 已选择的上级菜单信息 =====');
              console.log(`菜单ID: ${id}`);
              console.log(`菜单名称: ${menuName}`);
              console.log(`菜单类型: ${menuTypeText}`);
              console.log(`菜单路径: ${menuPath}`);
              console.log(`组件路径: ${component}`);
              console.log('===============================');
              
              // 根据选择的菜单路径自动更新生成模块名和包路径
              if (menuPath && menuPath !== '') {
                // 从路径中提取模块名（去除可能的前缀后缀）
                let moduleName = menuPath;
                
                // 如果有子路径（包含/），只取第一段
                if (moduleName.includes('/')) {
                  moduleName = moduleName.split('/')[0];
                }
                
                // 如果是外部链接（包含http://或https://），则不处理
                if (moduleName.startsWith('http://') || moduleName.startsWith('https://')) {
                  return true;
                }
                
                // 更新模块名
                const oldModuleName = this.info.moduleName;
                this.info.moduleName = moduleName;
                console.log(`自动更新：生成模块名从 "${oldModuleName}" 改为 "${moduleName}"`);
                
                // 更新包路径
                if (this.info.packageName) {
                  const packageParts = this.info.packageName.split('.');
                  if (packageParts.length > 0) {
                    const oldPackage = this.info.packageName;
                    // 替换最后一部分
                    packageParts[packageParts.length - 1] = moduleName;
                    this.info.packageName = packageParts.join('.');
                    console.log(`自动更新：包路径从 "${oldPackage}" 改为 "${this.info.packageName}"`);
                  }
                } else {
                  // 如果包路径为空，则直接设置为默认值加模块名
                  this.info.packageName = `com.hello.${moduleName}`;
                  console.log(`自动设置：包路径为 "${this.info.packageName}"`);
                }
                
                // 仅更新功能名，不自动设置业务名
                if (!this.info.functionName) {
                  this.info.functionName = menuName;
                  console.log(`自动更新：功能名为 "${menuName}"`);
                }
              }
              
              return true;
            }
            if (menus[i].children) {
              if (findMenuInfo(menus[i].children, id)) {
                return true;
              }
            }
          }
          return false;
        };
        
        // 调用查找函数
        if (this.menus && this.menus.length > 0) {
          findMenuInfo(this.menus, newVal);
        }
      }
    }
  },
  methods: {
    /** 切换卡片的收起/展开状态 */
    toggleCard(cardName) {
      this.cardVisible[cardName] = !this.cardVisible[cardName];
    },
    /** 处理模块名变化的联动效果 */
    handleModuleNameChange(newVal, oldVal) {
      // 只在有明确变化时执行
      if (!newVal || newVal === oldVal) return;
      
      console.log(`模块名从 ${oldVal} 变更为 ${newVal}`);
      
      // 1. 更新包路径中的模块部分，如果包路径格式为 com.hello.oldModule，改为 com.hello.newModule
      if (this.info.packageName && this.info.packageName.includes(oldVal)) {
        // 找到最后一段可能包含旧模块名的部分
        const parts = this.info.packageName.split('.');
        if (parts.length > 0 && parts[parts.length - 1] === oldVal) {
          parts[parts.length - 1] = newVal;
          this.info.packageName = parts.join('.');
          console.log(`已更新包路径为: ${this.info.packageName}`);
        }
      }
      
      // 2. 如果业务名为空或与旧模块名相同，则更新业务名
      if (!this.info.businessName || this.info.businessName === oldVal) {
        this.info.businessName = newVal;
        console.log(`已更新业务名为: ${newVal}`);
      }
      
      // 3. 如果生成功能名为空，更新功能名（通常是模块名的中文描述）
      if (!this.info.functionName) {
        this.info.functionName = newVal;
        console.log(`已更新功能名为: ${newVal}`);
      }
      
      // 4. 更新生成路径中的模块部分（如果存在）
      if (this.info.genPath) {
        // 检查路径中是否包含旧模块名
        const oldModulePattern = new RegExp(`[/\\\\]${oldVal}[/\\\\]`);
        if (oldModulePattern.test(this.info.genPath)) {
          // 获取路径分隔符
          let separator = '/';
          if (this.info.genPath.includes('\\')) {
            separator = '\\';
          }
          
          const newPath = this.info.genPath.replace(oldModulePattern, `${separator}${newVal}${separator}`);
          // 使用防抖更新所有相关路径
          this.debouncedUpdatePaths('genPath', newPath, this.info.genPath);
          this.info.genPath = newPath;
          console.log(`已更新生成路径为: ${newPath}`);
        }
      }
      
      // 5. 当模块名变更时，自动更新后端生成路径中的模块名部分
      if (this.info.backendGenPath) {
        // 获取路径分隔符
        let separator = '/';
        if (this.info.backendGenPath.includes('\\')) {
          separator = '\\';
        }
        
        const modulePattern = new RegExp(`${separator}hello-modules${separator}hello-[^${separator}]+`);
        if (modulePattern.test(this.info.backendGenPath)) {
          this.info.backendGenPath = this.info.backendGenPath.replace(modulePattern, `${separator}hello-modules${separator}hello-${newVal}`);
          this.originalPath.backendGenPath = this.info.backendGenPath;
          console.log(`已更新后端生成路径为: ${this.info.backendGenPath}`);
        }
      }
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.menuId,
        label: node.menuName,
        children: node.children
      };
    },
    /** 选择子表名触发 */
    subSelectChange(value) {
      this.info.subTableFkName = '';
    },
    /** 选择生成模板触发 */
    tplSelectChange(value) {
      if(value !== 'sub') {
        this.info.subTableName = '';
        this.info.subTableFkName = '';
      }
      this.generateFileStructure();
    },
    /** 设置关联外键 */
    setSubTableColumns(value) {
      for (var item in this.tables) {
        const name = this.tables[item].tableName;
        if (value === name) {
          this.subColumns = this.tables[item].columns;
          break;
        }
      }
    },
    /** 获取表单参数 - 提供给父组件调用 */
    getParams() {
      const params = {};
      
      // 树表参数
      if (this.info.tplCategory === 'tree') {
        params.treeCode = this.info.treeCode;
        params.treeParentCode = this.info.treeParentCode;
        params.treeName = this.info.treeName;
      }
      
      // 菜单参数
      if (this.info.parentMenuId) {
        params.parentMenuId = this.info.parentMenuId;
        
        // 查找菜单名称
        const findMenuName = (menus, id) => {
          console.log("查找菜单ID:", id, "当前菜单列表:", menus);
          for (let i = 0; i < menus.length; i++) {
            if (menus[i].menuId === id) {
              console.log("找到匹配的菜单:", menus[i].menuName);
              return menus[i].menuName;
            }
            if (menus[i].children) {
              const name = findMenuName(menus[i].children, id);
              if (name) {
                console.log("在子菜单中找到匹配:", name);
                return name;
              }
            }
          }
          return '';
        };
        
        const menuName = findMenuName(this.menus, this.info.parentMenuId);
        console.log("最终找到的菜单名称:", menuName, "菜单ID:", this.info.parentMenuId);
        params.parentMenuName = menuName || '系统管理'; // 确保至少有默认值
      } else {
        // 如果parentMenuId为空，设置默认值
        params.parentMenuId = "1"; // 默认系统管理
        params.parentMenuName = "系统管理";
      }
      
      // 添加合并模式参数
      params.mergeMode = this.info.mergeMode || "1";
      
      return params;
    },
    /** 显示目录选择对话框 */
    showDirectoryDialog(type) {
      this.directoryDialogVisible = true;
      this.currentPath = "";
      this.pathType = type;
      
      // 根据当前是否在编辑对话框中设置初始选中的路径
      if (this.pathInputVisible) {
        this.selectedPath = this.pathInputValue || "";
      } else {
        this.selectedPath = this.info[type] || "";
      }
      
      this.loadDirectories("");
    },
    /** 加载目录列表 */
    loadDirectories(path) {
      getSystemDirectories({ path: path }).then(response => {
        if (response.code === 200) {
          this.directories = response.data;
          this.currentPath = path || "";
        } else {
          this.$message.error(response.msg || "获取目录列表失败");
        }
      });
    },
    /** 选择目录 */
    selectDirectory(row) {
      this.selectedPath = row.path;
    },
    /** 进入子目录 */
    enterDirectory(row) {
      this.loadDirectories(row.path);
    },
    /** 导航到上一级目录 */
    navigateUp() {
      if (this.currentPath) {
        const pathParts = this.currentPath.split(/[/\\]/);
        pathParts.pop(); // 移除最后一部分
        const parentPath = pathParts.join('/');
        this.loadDirectories(parentPath);
      }
    },
    /** 确认目录选择 */
    confirmDirectorySelection() {
      if (this.selectedPath) {
        // 根据当前是否在编辑对话框中更新相应的路径
        if (this.pathInputVisible) {
          // 在编辑对话框中选择目录时，更新编辑框中的值
          this.pathInputValue = this.selectedPath;
        } else {
          // 直接选择目录时，更新info对象中的值
          const oldPath = this.info[this.pathType];
          this.info[this.pathType] = this.selectedPath;
          
          // 如果是主路径变化，应用防抖联动逻辑
          if (this.pathType === 'genPath') {
            this.debouncedUpdatePaths('genPath', this.selectedPath, oldPath);
          }
          
          // 更新原始路径值
          this.originalPath[this.pathType] = this.selectedPath;
        }
        this.directoryDialogVisible = false;
      } else {
        this.$message.warning("请先选择一个目录");
      }
    },
    /** 生成文件结构预览 */
    generateFileStructure() {
      // 确保info对象存在且包含必要属性
      if (!this.info || !this.info.packageName || !this.info.moduleName || !this.info.businessName) {
        return;
      }

      const packagePath = this.info.packageName.split(".").join("/");
      const moduleName = this.info.moduleName;
      const businessName = this.info.businessName;
      const className = this.info.className || this.toCapitalCase(businessName);
      const lowerClassName = this.toLowerFirstCase(className);

      // 1. 构建后端代码结构
      this.backendStructure = [
        {
          id: '1',
          name: 'src',
          isDirectory: true,
          children: [
            {
              id: '1-1',
              name: 'main',
              isDirectory: true,
              children: [
                {
                  id: '1-1-1',
                  name: 'java',
                  isDirectory: true,
                  children: [
                    {
                      id: '1-1-1-1',
                      name: packagePath,
                      isDirectory: true,
                      children: [
                        {
                          id: '1-1-1-1-1',
                          name: moduleName,
                          isDirectory: true,
                          children: [
                            {
                              id: '1-1-1-1-1-1',
                              name: 'controller',
                              isDirectory: true,
                              children: [{
                                id: '1-1-1-1-1-1-1',
                                name: `${className}Controller.java`,
                                isDirectory: false
                              }]
                            },
                            {
                              id: '1-1-1-1-1-2',
                              name: 'domain',
                              isDirectory: true,
                              children: [{
                                id: '1-1-1-1-1-2-1',
                                name: `${className}.java`,
                                isDirectory: false
                              }]
                            },
                            {
                              id: '1-1-1-1-1-3',
                              name: 'mapper',
                              isDirectory: true,
                              children: [{
                                id: '1-1-1-1-1-3-1',
                                name: `${className}Mapper.java`,
                                isDirectory: false
                              }]
                            },
                            {
                              id: '1-1-1-1-1-4',
                              name: 'service',
                              isDirectory: true,
                              children: [
                                {
                                  id: '1-1-1-1-1-4-1',
                                  name: `I${className}Service.java`,
                                  isDirectory: false
                                },
                                {
                                  id: '1-1-1-1-1-4-2',
                                  name: 'impl',
                                  isDirectory: true,
                                  children: [{
                                    id: '1-1-1-1-1-4-2-1',
                                    name: `${className}ServiceImpl.java`,
                                    isDirectory: false
                                  }]
                                }
                              ]
                            }
                          ]
                        }
                      ]
                    }
                  ]
                },
                {
                  id: '1-1-2',
                  name: 'resources',
                  isDirectory: true,
                  children: [
                    {
                      id: '1-1-2-1',
                      name: 'mapper',
                      isDirectory: true,
                      children: [
                        {
                          id: '1-1-2-1-1',
                          name: moduleName,
                          isDirectory: true,
                          children: [
                            {
                              id: '1-1-2-1-1-1',
                              name: `${className}Mapper.xml`,
                              isDirectory: false
                            }
                          ]
                        }
                      ]
                    }
                  ]
                }
              ]
            }
          ]
        }
      ];
      
      // 子表模板，添加子表相关文件
      if (this.info.tplCategory === 'sub' && this.info.subTableName) {
        const subClassName = this.toCapitalCase(this.info.subTableName.replace(/^.*_/, ''));
        const domainDir = this.backendStructure[0].children[0].children[0].children[0].children[0].children[1].children;
        domainDir.push({
          id: '1-1-1-1-1-2-2',
          name: `${subClassName}.java`,
          isDirectory: false
        });
      }

      // 2. 构建前端代码结构
      this.frontendStructure = [
        {
          id: '2',
          name: 'src',
          isDirectory: true,
          children: [
        {
          id: '2-1',
          name: 'api',
          isDirectory: true,
          children: [
            {
              id: '2-1-1',
              name: moduleName,
              isDirectory: true,
              children: [
                {
                  id: '2-1-1-1',
                  name: `${businessName}.js`,
                  isDirectory: false
                }
              ]
            }
          ]
        },
        {
          id: '2-2',
          name: 'views',
          isDirectory: true,
          children: [
            {
              id: '2-2-1',
              name: moduleName,
              isDirectory: true,
              children: [
                {
                  id: '2-2-1-1',
                  name: businessName,
                  isDirectory: true,
                  children: [
                    {
                      id: '2-2-1-1-1',
                      name: 'index.vue',
                      isDirectory: false
                        }
                      ]
                    }
                  ]
                }
              ]
            }
          ]
        }
      ];

      // 3. 构建配置代码结构
      this.configStructure = [
        {
          id: '3-1',
          name: 'sql',
          isDirectory: true,
          children: [
            {
              id: '3-1-1',
              name: `${businessName}Menu.sql`,
              isDirectory: false
            }
          ]
        }
      ];

      // 根据模板类型添加其他配置
      if (this.info.tplCategory === 'tree') {
        this.configStructure.push({
          id: '3-2',
          name: 'config',
          isDirectory: true,
          children: [
            {
              id: '3-2-1',
              name: `${businessName}TreeConfig.json`,
              isDirectory: false
            }
          ]
        });
      }
    },
    /** 首字母大写 */
    toCapitalCase(str) {
      if (!str) return '';
      return str.charAt(0).toUpperCase() + str.slice(1);
    },
    /** 首字母小写 */
    toLowerFirstCase(str) {
      if (!str) return '';
      return str.charAt(0).toLowerCase() + str.slice(1);
    },
    /** 同步获取项目根路径 */
    setProjectRootPathSync() {
      // 如果已有路径且不是默认值，则不更新
      if (this.info.genPath && this.info.genPath !== '/' && this.info.genPath !== '/dev-api') {
        return;
      }
      
      // 同步方式获取工作空间路径
      try {
        // 先设置一个默认值
        this.info.genPath = this.info.genPath || '/';
        
        // 修复可能错误的API路径
        if (this.info.genPath === '/dev-api') {
          this.info.genPath = '/';
        }
        
        // 如果前后端路径使用了错误的API路径，也进行修复
        if (this.info.backendGenPath === '/dev-api') {
          this.info.backendGenPath = this.info.genPath;
        }
        
        if (this.info.frontendGenPath === '/dev-api') {
          this.info.frontendGenPath = this.info.genPath;
        }
        
        // 再异步获取真实路径
        getWorkspace().then(res => {
          if (res.code === 200 && res.data && res.data.workspace) {
            // 仅当当前路径为默认值时才更新
            if (this.info.genPath === '/' || this.info.genPath === '/dev-api') {
              this.info.genPath = res.data.workspace;
              
              // 获取操作系统信息
              const isWindows = res.data.osName && res.data.osName.toLowerCase().includes("windows");
              // 根据操作系统选择分隔符
              const separator = isWindows ? '\\' : '/';
              
              // 同步更新前后端路径，自动添加适当的子目录
              if (!this.info.backendGenPath || this.info.backendGenPath === '/' || this.info.backendGenPath === '/dev-api') {
                this.info.backendGenPath = this.info.genPath + separator + "hello-modules" + separator + "hello-" + this.info.moduleName;
              }
              if (!this.info.frontendGenPath || this.info.frontendGenPath === '/' || this.info.frontendGenPath === '/dev-api') {
                this.info.frontendGenPath = this.info.genPath + separator + "hello-ui";
              }
            }
          }
        }).catch(() => {
          console.error('获取工作空间路径失败');
        });
      } catch (error) {
        console.error('设置项目路径出错:', error);
      }
    },
    /** 设置项目根路径 */
    setProjectRootPath() {
      getWorkspace().then(res => {
        if (res.code === 200 && res.data) {
          const oldPath = this.info.genPath;
          this.info.genPath = res.data.workspace || this.info.genPath;
          
          // 获取操作系统信息
          const isWindows = res.data.osName && res.data.osName.toLowerCase().includes("windows");
          // 根据操作系统选择分隔符
          const separator = isWindows ? '\\' : '/';
          
          // 更新前后端路径，添加适当的子目录
          if (!this.info.backendGenPath || this.info.backendGenPath === oldPath) {
            this.info.backendGenPath = this.info.genPath + separator + "hello-modules" + separator + "hello-" + this.info.moduleName;
          }
          if (!this.info.frontendGenPath || this.info.frontendGenPath === oldPath) {
            this.info.frontendGenPath = this.info.genPath + separator + "hello-ui";
          }
          
          // 使用防抖函数处理路径联动
          this.debouncedUpdatePaths('genPath', this.info.genPath, oldPath);
          
          // 更新原始路径
          this.originalPath.genPath = this.info.genPath;
          this.originalPath.backendGenPath = this.info.backendGenPath;
          this.originalPath.frontendGenPath = this.info.frontendGenPath;
        }
      }).catch(() => {
        // 如果获取失败，使用默认路径
        const oldPath = this.info.genPath;
        this.info.genPath = this.info.genPath || '/';
        
        // 使用防抖函数处理路径联动
        this.debouncedUpdatePaths('genPath', this.info.genPath, oldPath);
        
        // 更新原始路径
        this.originalPath.genPath = this.info.genPath;
      });
    },
    /** 编辑路径 */
    editPath(type) {
      // 保存当前正在编辑的路径类型
      this.currentEditPathType = type;
      // 保存原始值，以便在取消时恢复
      this.originalPath[type] = this.info[type];
      // 设置当前编辑的路径值
      this.pathInputValue = this.info[type] || '';
      // 显示编辑对话框
      this.pathInputVisible = true;
    },
    /** 保存编辑后的路径 */
    saveEditedPath() {
      // 保存旧路径用于比较
      const oldPath = this.info[this.currentEditPathType];
      
      // 设置修改后的路径
      this.info[this.currentEditPathType] = this.pathInputValue;
      
      // 如果是主路径，更新前后端路径的基础
      if (this.currentEditPathType === 'genPath') {
        // 使用防抖函数处理路径联动
        this.debouncedUpdatePaths('genPath', this.pathInputValue, oldPath);
        
        // 提示路径已更新
        this.$message({
          message: '工作空间路径已更新，前端和后端路径也会相应更新',
          type: 'success'
        });
      } else {
        // 提示路径已更新
        this.$message({
          message: '路径已更新',
          type: 'success'
        });
      }
      
      // 更新原始路径
      this.originalPath[this.currentEditPathType] = this.pathInputValue;
      
      // 关闭对话框
      this.pathInputVisible = false;
    },
    /** 设置默认路径 */
    setDefaultPath() {
      // 获取实际工作空间路径
      getWorkspace().then(res => {
        if (res.code === 200 && res.data && res.data.workspace) {
          const oldPath = this.info.genPath;
          this.info.genPath = res.data.workspace;
          
          // 使用防抖函数处理路径联动
          this.debouncedUpdatePaths('genPath', this.info.genPath, oldPath);
          
          // 更新原始路径
          this.originalPath.genPath = this.info.genPath;
          
          // 提示用户
          this.$message({
            message: '已设置为项目工作空间路径',
            type: 'success'
          });
        } else {
          const oldPath = this.info.genPath;
          this.info.genPath = '/';
          
          // 使用防抖函数处理路径联动
          this.debouncedUpdatePaths('genPath', this.info.genPath, oldPath);
          
          // 更新原始路径
          this.originalPath.genPath = this.info.genPath;
          
          // 提示用户
          this.$message({
            message: '已恢复默认工作空间路径',
            type: 'success'
          });
        }
      }).catch(() => {
        const oldPath = this.info.genPath;
        this.info.genPath = '/';
        
        // 使用防抖函数处理路径联动
        this.debouncedUpdatePaths('genPath', this.info.genPath, oldPath);
        
        // 更新原始路径
        this.originalPath.genPath = this.info.genPath;
        
        // 提示用户
        this.$message({
          message: '已恢复默认工作空间路径',
          type: 'success'
        });
      });
    },
    /** 生成全部代码 */
    generateAllCode() {
      // 先保存配置
      this.saveConfigAndGenerate('all');
    },
    /** 生成后端代码 */
    generateBackendCode() {
      // 先保存配置
      this.saveConfigAndGenerate('backend');
    },
    /** 生成前端代码 */
    generateFrontendCode() {
      // 先保存配置
      this.saveConfigAndGenerate('frontend');
    },
    /** 保存配置并生成代码 */
    saveConfigAndGenerate(codeType) {
      if (!this.info || !this.info.tableName) {
        this.$modal.msgError("无法获取表名，请保存配置后再生成代码");
        return;
      }

      // 获取表名
      const tableName = this.info.tableName;
      
      // 直接生成代码
            if (codeType === 'all') {
              // 生成全部代码
              this.generateCode(tableName, "全部");
            } else if (codeType === 'backend') {
              // 生成后端代码
              this.generateCode(tableName, "后端", this.info.backendGenPath);
            } else if (codeType === 'frontend') {
              // 生成前端代码
              this.generateCode(tableName, "前端", this.info.frontendGenPath);
      }
    },
    /** 调用代码生成API */
    generateCode(tableName, codeTypeDesc, specificPath) {
      // 获取对应的生成路径
      let genPath = '';
      
      if (specificPath) {
        // 如果提供了特定路径，直接使用
        genPath = specificPath;
      } else {
        // 否则根据类型选择路径
        if (codeTypeDesc === '全部') {
          genPath = this.info.genPath || '/';
        } else if (codeTypeDesc === '后端') {
          genPath = this.info.backendGenPath || this.info.genPath || '/';
        } else if (codeTypeDesc === '前端') {
          genPath = this.info.frontendGenPath || this.info.genPath || '/';
        }
      }
      
      // 添加生成路径
      const params = {};
      params.genPath = genPath;
      
      // 根据代码类型设置参数
      if (codeTypeDesc === '后端') {
        params.codeType = 'backend';
      } else if (codeTypeDesc === '前端') {
        params.codeType = 'frontend';
      }
      
      // 添加合并模式参数
      params.mergeMode = this.info.mergeMode || "1";
      
      // 添加菜单信息参数
      if (this.info.parentMenuId) {
        params.parentMenuId = this.info.parentMenuId;
      }
      
      // 强制添加父菜单信息，即使后端会重置也要传递
      const parentMenuName = this.getParentMenuName();
      if (parentMenuName) {
        params.parentMenuName = parentMenuName;
      }
      
      console.log("生成代码参数:", params);
      
      // 显示生成中提示
      this.$modal.loading("正在生成代码...");
      
      // 调用API生成代码
      genCode(tableName, params).then(() => {
        this.$modal.closeLoading();
        this.$modal.msgSuccess(`${codeTypeDesc}代码生成成功，已生成到路径: ${genPath}`);
      }).catch(err => {
        this.$modal.closeLoading();
        this.$modal.msgError(`${codeTypeDesc}代码生成失败: ${err.msg || err.message || "未知错误"}`);
      });
    },
    
    /** 获取父菜单名称 */
    getParentMenuName() {
      if (!this.info.parentMenuId || !this.menus) {
        return "系统管理"; // 默认值
      }
      
      // 递归查找菜单名称
      const findMenuName = (menus, id) => {
        for (let i = 0; i < menus.length; i++) {
          if (menus[i].menuId == id) {
            return menus[i].menuName;
          }
          if (menus[i].children) {
            const name = findMenuName(menus[i].children, id);
            if (name) {
              return name;
            }
          }
        }
        return null;
      };
      
      const menuName = findMenuName(this.menus, this.info.parentMenuId);
      return menuName || "系统管理";
    },
    /** 更新相关路径（添加防抖功能） */
    updateRelatedPaths(sourceType, newVal, oldVal) {
      console.log(`路径更新: ${sourceType} 从 ${oldVal} 变为 ${newVal}`);
      
      if (sourceType === 'genPath') {
        // 判断后端路径是否需要更新（为空或等于旧的主路径）
        const shouldUpdateBackend = !this.info.backendGenPath || 
                                   this.info.backendGenPath === oldVal || 
                                   this.info.backendGenPath === '/dev-api' ||
                                   this.info.backendGenPath === '/';
                                   
        // 判断前端路径是否需要更新（为空或等于旧的主路径）
        const shouldUpdateFrontend = !this.info.frontendGenPath || 
                                    this.info.frontendGenPath === oldVal || 
                                    this.info.frontendGenPath === '/dev-api' ||
                                    this.info.frontendGenPath === '/';
        
        // 获取路径分隔符
        let separator = '/';
        if (newVal.includes('\\')) {
          separator = '\\';
        }
        
        // 更新后端路径，自动添加适当的子目录
        if (shouldUpdateBackend) {
          this.info.backendGenPath = newVal + separator + "hello-modules" + separator + "hello-" + this.info.moduleName;
          this.originalPath.backendGenPath = this.info.backendGenPath;
          console.log(`已同步更新后端路径为: ${this.info.backendGenPath}`);
        }
        
        // 更新前端路径，自动添加适当的子目录
        if (shouldUpdateFrontend) {
          this.info.frontendGenPath = newVal + separator + "hello-ui";
          this.originalPath.frontendGenPath = this.info.frontendGenPath;
          console.log(`已同步更新前端路径为: ${this.info.frontendGenPath}`);
        }
      }
    },
    /** 添加@input事件监听 */
    onGenPathInput(val) {
      // 使用防抖函数处理主路径变化
      this.debouncedUpdatePaths('genPath', val, this.originalPath.genPath);
      // 更新原始路径，用于后续比较
      this.originalPath.genPath = val;
    },
    onBackendPathInput(val) {
      // 更新原始路径，但不触发其他路径更新
      this.originalPath.backendGenPath = val;
    },
    onFrontendPathInput(val) {
      // 更新原始路径，但不触发其他路径更新
      this.originalPath.frontendGenPath = val;
    },
    /** 处理模块名输入事件 */
    onModuleNameInput(val) {
      console.log("模块名输入变化:", val, "原始值:", this.originalPath.moduleName);
      
      // 如果后端路径存在，立即更新后端路径
      if (this.info.backendGenPath) {
        // 获取路径分隔符
        let separator = '/';
        if (this.info.backendGenPath.includes('\\')) {
          separator = '\\';
        }
        
        // 直接构建新的后端路径
        const basePath = this.info.genPath || '';
        const newBackendPath = `${basePath}${separator}hello-modules${separator}hello-${val}`;
        
        // 检查路径是否已经变更
        if (this.info.backendGenPath !== newBackendPath) {
          console.log(`后端路径从 ${this.info.backendGenPath} 更新为 ${newBackendPath}`);
          this.info.backendGenPath = newBackendPath;
        }
      }
      
      // 更新包名中的模块名部分（如果最后一部分匹配旧模块名）
      if (this.info.packageName && this.originalPath.moduleName) {
        const parts = this.info.packageName.split('.');
        if (parts.length > 0 && parts[parts.length - 1] === this.originalPath.moduleName) {
          parts[parts.length - 1] = val;
          this.info.packageName = parts.join('.');
          console.log(`已更新包路径为: ${this.info.packageName}`);
        }
      }
      
      // 更新业务名（如果与旧模块名相同）
      if (this.info.businessName === this.originalPath.moduleName) {
        this.info.businessName = val;
        console.log(`已更新业务名为: ${val}`);
      }
      
      // 更新功能名（如果为空或与旧模块名相同）
      if (!this.info.functionName || this.info.functionName === this.originalPath.moduleName) {
        this.info.functionName = val;
        console.log(`已更新功能名为: ${val}`);
      }
      
      // 记录当前模块名，用于下一次比较
      this.originalPath.moduleName = val;
      
      // 重新生成文件结构预览
      this.generateFileStructure();
    },
    
    /** 处理包路径输入事件 */
    onPackageNameInput(val) {
      // 使用防抖处理包路径变化
      this.debouncedPackageNameChange(val);
    },
    /** 切换后端代码结构折叠状态 */
    toggleBackendCollapse() {
      this.backendCollapsed = !this.backendCollapsed;
    },
    /** 切换前端代码结构折叠状态 */
    toggleFrontendCollapse() {
      this.frontendCollapsed = !this.frontendCollapsed;
    },
    /** 切换配置代码结构折叠状态 */
    toggleConfigCollapse() {
      this.configCollapsed = !this.configCollapsed;
    },
    /** 切换树的展开状态 */
    toggleTreeExpand(treeRef) {
      if (treeRef === 'backendTree') {
        if (this.isBackendTreeExpanded) {
          this.collapseTree(treeRef);
          this.isBackendTreeExpanded = false;
        } else {
          this.expandTree(treeRef);
          this.isBackendTreeExpanded = true;
        }
      } else if (treeRef === 'frontendTree') {
        if (this.isFrontendTreeExpanded) {
          this.collapseTree(treeRef);
          this.isFrontendTreeExpanded = false;
        } else {
          this.expandTree(treeRef);
          this.isFrontendTreeExpanded = true;
        }
      } else if (treeRef === 'configTree') {
        if (this.isConfigTreeExpanded) {
          this.collapseTree(treeRef);
          this.isConfigTreeExpanded = false;
        } else {
          this.expandTree(treeRef);
          this.isConfigTreeExpanded = true;
        }
      }
    },
    /** 切换所有结构的展开状态 */
    toggleAllStructures() {
      if (this.allExpanded) {
        this.collapseAllStructures();
      } else {
        this.expandAllStructures();
      }
      this.allExpanded = !this.allExpanded;
    },
    /** 展开所有结构 */
    expandAllStructures() {
      this.backendCollapsed = false;
      this.frontendCollapsed = false;
      this.configCollapsed = false;
      
      // 等待DOM更新后展开所有树
      this.$nextTick(() => {
        this.expandTree('backendTree');
        this.expandTree('frontendTree');
        this.expandTree('configTree');
        
        // 更新展开状态
        this.isBackendTreeExpanded = true;
        this.isFrontendTreeExpanded = true;
        this.isConfigTreeExpanded = true;
      });
    },
    /** 折叠所有结构 */
    collapseAllStructures() {
      this.backendCollapsed = true;
      this.frontendCollapsed = true;
      this.configCollapsed = true;
      
      // 更新展开状态
      this.isBackendTreeExpanded = true;
      this.isFrontendTreeExpanded = true;
      this.isConfigTreeExpanded = true;
    },
    /** 刷新所有结构 */
    refreshAllStructures() {
      this.generateFileStructure();
      this.$message({
        message: '文件结构已刷新',
        type: 'success'
      });
    },
    /** 展开指定的树 */
    expandTree(treeRef) {
      if (this.$refs[treeRef]) {
        const tree = this.$refs[treeRef];
        const nodes = tree.store._getAllNodes();
        nodes.forEach(node => {
          node.expanded = true;
        });
      }
    },
    
    /** 折叠指定的树 */
    collapseTree(treeRef) {
      if (this.$refs[treeRef]) {
        const tree = this.$refs[treeRef];
        const nodes = tree.store._getAllNodes();
        // 只折叠第一层以下的节点，保持第一层展开
        nodes.forEach(node => {
          if (node.level > 1) {
            node.expanded = false;
          }
        });
      }
    },
    // 预览代码
    previewCode() {
      console.log("预览代码按钮被点击");
      
      if (!this.info || !this.info.tableId) {
        console.error("表信息不存在", this.info);
        this.$modal.msgError("表信息不存在");
        return;
      }
      
      console.log("开始预览代码，tableId:", this.info.tableId);
      
      // 使用previewTable API直接预览代码
      previewTable(this.info.tableId).then(response => {
        console.log("预览代码API返回成功", response);
        // 触发自定义事件，传递预览数据
        this.$emit('preview-data', {
          data: response.data,
          tableId: this.info.tableId
        });
      }).catch(error => {
        console.error("预览代码失败:", error);
        this.$modal.msgError("预览代码失败，请重试");
      });
    },
  }
};
</script>

<style scoped>
/* 基本容器样式 */
.app-container {
  height: 100%;
  padding: 20px;
}

/* 表格样式 */
.common-table {
  margin-top: 15px;
}

.common-table >>> .el-table__header th {
  background-color: #f8f8f9;
  color: #606266;
  font-weight: bold;
  padding: 10px 0;
}

.common-table >>> .el-table__row:hover td {
  background-color: #f0f7ff !important;
}

.common-table >>> .el-table__row.current-row td {
  background-color: #e6f7ff !important;
}

/* 标签类型样式 */
.el-tag.el-tag--primary {
  background-color: #ecf5ff;
  border-color: #d9ecff;
  color: #409eff;
  font-weight: bold;
}

.el-tag.el-tag--success {
  background-color: #f0f9eb;
  border-color: #e1f3d8;
  color: #67c23a;
  font-weight: bold;
}

.el-tag.el-tag--warning {
  background-color: #fdf6ec;
  border-color: #faecd8;
  color: #e6a23c;
  font-weight: bold;
}

/* 菜单选择器和表单项样式 */
.menu-select {
  width: 100%;
}

/* 重要表单项样式 - 增强视觉效果 */
.important-form-item {
  background-color: #f8faff;
  padding: 15px;
  border-radius: 6px;
  border-left: 3px solid #409eff;
  transition: all 0.3s ease;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.03);
  margin-bottom: 20px;
}

.important-form-item:hover {
  background-color: #eef5ff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.important-form-item .el-form-item__label {
  font-weight: 600;
}

/* 表单项间距和对齐 */
.el-form-item {
  margin-bottom: 18px;
}

.el-form-item__content {
  line-height: 32px;
}

/* 结构预览项样式 */
.structure-preview-item .el-form-item__content {
  margin-left: 0 !important;
}

.structure-preview-item .el-form-item__label {
  display: none;
}

/* 卡片组件样式 */
.box-card {
  margin-bottom: 20px;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05) !important;
}

.box-card .el-card__header {
  padding: 12px 20px;
  font-weight: 600;
  background-color: #f6f8fa;
  border-bottom: 1px solid #ebeef5;
}

.box-card .el-card__body {
  padding: 15px 20px;
}

/* 优化表单项和元素间距 */
.el-row {
  margin-bottom: 10px;
}

.el-col {
  margin-bottom: 10px;
}

/* 美化上级菜单选择器 */
.el-select.is-focus .el-input__inner,
.menu-select.vue-treeselect.vue-treeselect--focused:not(.vue-treeselect--disabled) .vue-treeselect__control {
  border-color: #409EFF;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 简化的输入和按钮样式 */
.box-card.is-collapsed .el-card__body .el-form-item__content .el-input__inner {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-family: monospace;
  font-size: 13px;
}

.box-card.is-collapsed .el-card__body .el-form-item__content .el-input__inner:hover {
  overflow: visible;
  white-space: normal;
  height: auto;
  z-index: 999;
  position: relative;
  background-color: #fff;
  border-color: #409EFF;
}

.box-card.is-collapsed .el-card__body .el-form-item__content .el-input__append {
  padding: 0;
}

.box-card.is-collapsed .el-card__body .el-form-item__content .el-input__append .el-button {
  padding: 5px 8px;
  margin: 0;
  border: 0;
  background-color: transparent;
}

.box-card.is-collapsed .el-card__body .el-form-item__content .el-input__append .el-button:hover {
  background-color: #f0f5ff;
}

.box-card.is-collapsed .el-card__body .el-form-item__content .el-input__append .el-button:active {
  background-color: #e1f3d8;
}

.box-card.is-collapsed .el-card__body .el-form-item__content .el-input__append .el-button:focus {
  outline: none;
}

.box-card.is-collapsed .el-card__body .el-form-item__content .el-input__append .el-button:disabled {
  background-color: #f0f5ff;
}

.box-card.is-collapsed .el-card__body .el-form-item__content .el-input__append .el-button:disabled:hover {
  background-color: #f0f5ff;
}

.box-card.is-collapsed .el-card__body .el-form-item__content .el-input__append .el-button:disabled:active {
  background-color: #f0f5ff;
}

.box-card.is-collapsed .el-card__body .el-form-item__content .el-input__append .el-button:disabled:focus {
  outline: none;
}

/* 卡片头部样式 - 添加收起展开按钮 */
.clearfix {
  position: relative;
}

.collapse-icon {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  transition: transform 0.3s;
  color: #909399;
}

.collapse-icon:hover {
  color: #409EFF;
}

/* 目录对话框样式 */
.directory-dialog {
  display: flex;
  flex-direction: column;
}

.directory-tree-container {
  padding: 10px;
}

.directory-form {
  margin-bottom: 10px;
  width: 100%;
}

.path-item {
  width: 100%;
  margin-right: 0;
}

/* 路径输入框样式 */
::v-deep .el-input__inner {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  font-family: monospace;
  font-size: 13px;
}

/* 路径输入框悬停效果 */
::v-deep .path-item .el-input__inner:hover {
  overflow: visible;
  white-space: normal;
  height: auto;
  z-index: 999;
  position: relative;
  background-color: #fff;
  border-color: #409EFF;
}

.directory-list {
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  margin-bottom: 10px;
}

.dir-item {
  display: flex;
  align-items: center;
  padding: 2px 0;
}

/* 对话框底部 */
.dialog-footer {
  padding: 10px 20px;
  text-align: right;
}

/* 文件结构预览相关 */
.file-structure-preview {
  margin-top: 10px;
}

.file-structure-preview-header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}

.tree-operations {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}

/* 设置文件结构树形区域样式 */
.el-tree {
  margin: 5px 0;
  background-color: #fafbfc;
  border-radius: 4px;
  padding: 8px;
  border: 1px solid #ebeef5;
}

.el-tree .el-tree-node__content {
  height: 28px;
}

.custom-tree-node {
  font-size: 13px;
  padding: 2px 0;
}

/* 给嵌套卡片额外的样式 */
.file-structure-preview .el-card {
  box-shadow: 0 1px 8px 0 rgba(0, 0, 0, 0.03) !important;
}

.file-structure-preview .el-card .el-card__header {
  padding: 10px 15px;
  background-color: #f8f9fa;
}

.file-structure-preview .el-tag {
  margin-bottom: 5px;
}

/* 响应式布局调整 */
@media (max-width: 768px) {
  .el-form-item__label {
    float: none;
    display: block;
    text-align: left;
    padding: 0 0 10px;
  }
  
  .el-form-item__content {
    margin-left: 0 !important;
  }
  
  .el-col {
    width: 100% !important;
  }
}
</style>
